<template>
  <view class="containerDoc">
    <view class="page-container" :style="listHeightStylePage">
      <u-navbar :title="titlesp" placeholder @leftClick="rightClick" :border="false" :shadow="true"></u-navbar>
      <!-- 导航栏 -->
      <view class="topdiv" style="height: 160rpx; flex-shrink: 0;">
        <up-tabs :list="tabs" :current="currentIndex" :scrollable="false" @click="clickTabs"></up-tabs>
        <view class="view-search">
          <u-search placeholder="请输入关键字" v-model="keywords" :showAction="false" @change="changeSearch"></u-search>
        </view>
      </view>

      <view :style="listHeightStyle">
        <scroll-view :style="listHeightStyle" :scroll-top="scrollTop" :refresher-background="'transparent'"
          class="apply-menu" scroll-y="true" :refresher-enabled="true" :refresher-triggered="isRefreshing"
          @refresherrefresh="onRefresh" @scrolltolower="loadMore">
          <!-- @click="goJumpTo(item)" -->
          <view v-for="(item, index) in list" :key="index" class="list-item" @click="handleItemClick(index)">
            <view class="list-li">

              <view class="title-container">
                <up-checkbox :customStyle="{ margin: '0', display: 'inline-block', verticalAlign: 'middle' }"
                  :name="item.id" usedAlone v-model:checked="aloneChecked[index]">
                </up-checkbox>
                <view class="title-text">{{ item.title }}</view>
              </view>


              <view class="applicant">申请人: {{ item.create_name }}</view>


              <view class="tip" v-for="(r, idx) in item.tip" :key="idx">{{ r }}</view>


              <view class="time-info">
                <view v-if="item.create_time">发起时间: {{ item.create_time }}</view>
                <view v-if="item.end_time">完成时间: {{ item.end_time }}</view>
              </view>


              <up-divider></up-divider>


              <view class="status" :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </view>
            </view>
          </view>


          <view v-if="loading" class="loading-text">
            加载中...
          </view>


          <view v-if="noMore" class="no-more-text">
            没有更多数据了
          </view>

        </scroll-view>

      </view>


      <view class="bottom-btn">
        <up-button class="boUpbut" type="primary" text="确定" @click="sumbit"></up-button>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
import componentMinxins from '../ComponentMinxins'
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js"
import org from '@/apis/cloud/org.js'

export default {
  mixins: [componentMinxins, MescrollMixin],
  data () {
    return {
      show: false,
      titlesp: '审批单列表',
      tabs: [
        {
          name: "全部"
        },
        {
          name: "待处理"
        },
        {
          name: "已处理"
        },
        {
          name: "已发起"
        },
        {
          name: "抄送我的"
        }
      ],
      upOption: {
        page: {
          size: 10 // 每页数据的数量,默认10
        },
        noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
        empty: {
          tip: '暂无更多...'
        }
      },
      total: 0,
      queryParams: {
        pageSize: 15,
        pageNum: 1
      },
      list: [],
      keywords: '', //搜索关键字
      type: '', //搜索下拉框
      currentIndex: 0,
      aloneChecked: [],
      checkData: [],
      loading: false,
      noMore: false,
      isRefreshing: false,
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      listHeightStylePage: {},
      doc: [],
      itemId: null,
      height: 0,
      scrollTop: 0
    }
  },
  onLoad (option) {
    this.itemId = option.itemId;

    if (option.checkData) {
      this.checkData = JSON.parse(option.checkData)
    }

    if (option.doc) {
      this.doc = JSON.parse(option.doc)
    }


  },
  onReady () {

  },
  computed: {
    ...mapStores(useUserStore)
  },
  created () {

    this.height = (uni.getSystemInfoSync().windowHeight || uni.getSystemInfoSync().screenHeight) || 0
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${this.height}px`,
      overflow: 'hidden'
    };


    this.listHeightStyle = {
      height: `${this.height - 180}px`,
      overflowY: 'auto'
    };
    // #endif

    // #ifdef APP-PLUS
    this.listHeightStylePage = {
      height: `${this.height}px`,
      overflow: 'hidden'
    };

    this.listHeightStyle = {
      height: `${this.height - 200}px`,
      overflowY: 'auto'
    };

    // #endif
    this.getInfo();
  },
  mounted () {
    let value = uni.getStorageSync('formData');
    let formItems = JSON.parse(value.formItems);
    formItems.forEach(item => {
      if (item.title == this.title) {
        uni.removeStorageSync(`${item.id}`);
      }
    })
  },
  watch: {
    checkData: {
      handler (newValue) {
        let value = uni.getStorageSync('formData');
        let formItems = JSON.parse(value.formItems);
        formItems.forEach(item => {
          if (item.title == this.title) {
            uni.removeStorageSync(item.id);
            let filteredData = newValue.map(data => ({
              id: data.id,
              title: data.title
            }));
            item.value = newValue[0];
            uni.setStorageSync(item.id, filteredData);
          }
        })
      },
      deep: true
    }
  },
  methods: {
    handleItemClick (index) {
      this.aloneChecked[index] = !this.aloneChecked[index];
    },
    initAloneChecked () {
      const selectedIds = this.checkData?.map(item => item.id) || [];
      this.aloneChecked = this.list.map(item => selectedIds.includes(item.id));
    },
    goJumpTo (item) {
      uni.navigateTo({
        url: '/pages/apply/oaList/applyOrderDetail?id=' + item.id
      });
    },
    changeSearch (e) {
      this.getInfo()
    },
    clickTabs (item) {
      this.currentIndex = item.index
      this.list = [];
      this.queryParams.pageNum = 1;
      this.noMore = false;
      this.getInfo();
      this.scrollTop = 0;
      this.$nextTick(() => {
        this.scrollTop = 1;
        this.$nextTick(() => {
          this.scrollTop = 0;
        });
      });
    },
    getStatusText (status) {
      const statusMap = {
        1: '审批中',
        2: '审批同意',
        3: '审批驳回',
        4: '审批撤销',
      };
      return statusMap[status] || '';
    },
    // 获取状态样式类
    getStatusClass (status) {
      return `status-${status}`;
    },
    onRefresh () {
      this.isRefreshing = true; // 开始刷新
      this.list = [];
      this.queryParams.pageNum = 1;
      this.noMore = false;
      return this.getInfo();
    },
    loadMore () {
      if (this.loading || this.noMore) return;
      this.queryParams.pageNum++;
      this.getInfo();
    },
    refreshList () {
      this.list = [];
      this.queryParams.pageNum = 1;
      this.noMore = false;
      return this.getInfo();
    },
    getInfo () {
      // 显示加载框

      if (this.loading) {
        // 隐藏加载框
        uni.hideLoading();
        return
      }
      this.loading = true;

      let jsonData = {
        keywords: this.keywords,
        page: this.queryParams.pageNum,
        row: this.queryParams.pageSize,
        active: this.currentIndex,
        state: 0,
        type: this.type ? this.type : '',
        doc: this.doc ? this.doc?.join(',') : []
      }

      try {
        uni.showLoading({
          title: '加载中'
        });
        org.getApply(jsonData).then(res => {
          if (res.status > 0) {
            this.list = this.queryParams.pageNum === 1 ? res.data : [...this.list, ...res.data];
            this.total = res.total;
            if (this.list.length >= this.total) {
              this.noMore = true;
            }
            this.isRefreshing = false;
            this.loading = false;
            uni.hideLoading();
          } else {
            this.loading = false;
            this.noMore = true;
            this.isRefreshing = false;
            uni.hideLoading();
          }
          // 初始化勾选状态（如果 list 是静态的，可以立即初始化）
          this.initAloneChecked();
        })
      } catch (err) {
        uni.hideLoading();
        this.loading = false;
        this.isRefreshing = false;
        console.error('请求失败', err);
      } finally {
        // 隐藏加载框

        // this.loading = false;
      }
    },

    openPopup () {
      this.show = true;
    },
    rightClick () {
      uni.navigateBack({ delta: 1 });
    },
    search () {

    },
    sumbit () {
      this.checkData = [];
      this.list.forEach((item, i) => {
        this.aloneChecked.forEach((row, k) => {
          if (i == k && row) {
            this.checkData.push({
              ...item,
              itemId: this.itemId
            })
          }
        })
      })
      uni.$emit('AssociationTableList', {
        itemId: this.itemId,
        data: this.checkData
      })
      this.rightClick()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 加载中和无更多数据提示 */
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.title-container {
  display: flex;
  /* 使用 flex 布局 */
  align-items: center;
  /* 垂直居中对齐 */
  gap: 16rpx;
  /* 复选框和标题之间的间距 */
  margin-bottom: 10rpx;
  /* 标题与下方内容的间距 */
}

.title-text {
  font-size: 32rpx;
  /* 标题字体大小 */
  font-weight: bold;
  /* 加粗显示 */
  color: #333;
  /* 标题颜色 */
  flex: 1;
  /* 占据剩余空间 */
  overflow: hidden;
  /* 防止文本溢出 */
  text-overflow: ellipsis;
  /* 省略号处理长文本 */
  white-space: nowrap;
  /* 禁止换行 */
}

.containerDoc {
  background-color: #ffffff;
}

::v-deep .u-tabs__wrapper {
  background-color: white;
}

.view-search {
  background-color: white;

  .search {
    padding: 10rpx 0rpx 10rpx 0rpx;
  }

  ::v-deep .u-search__content {
    margin: 20rpx 20rpx 20rpx 20rpx !important;
  }
}

.list-li {
  margin-left: 30rpx;
  padding-top: 20rpx;
  padding-bottom: 10rpx;
}

::v-deep .u-divider {
  margin: 10px 0px 0px 0px;
}

.topdiv {
  flex-shrink: 0;
  /* 固定高度，不被压缩 */
  background-color: white;
  z-index: 1;
  /* 防止被内容覆盖 */
}

.popup {
  padding: 36rpx 0rpx;

  .popup-content {
    margin: 20rpx 10rpx 20rpx 40rpx;
  }
}

.input-first {
  border: 1rpx solid #dadbde;
  display: inline-block;
  width: 420rpx;

  background-color: white !important;
}

.input {
  border: 1rpx solid #dadbde;
  display: inline-block;
  width: 420rpx;
  pointer-events: none;
  background-color: white !important;
}

.span {
  display: inline-block;
  width: 230rpx;
}

.btn {
  display: inline-block;
  width: 280rpx;
  margin-right: 50rpx;
}

.btnS {
  display: inline-block;
  width: 280rpx;
}

.bottom-btn {
  height: 40px;
  margin-top: 5px;
  width: 100%;
  margin-bottom: 5px;

  .boUpbut {
    width: 90vw;
  }
}

.check-data-container {
  display: flex;
  flex-wrap: wrap; // 如果内容过多则自动换行
  gap: 20rpx; // 设置间距
  padding: 20rpx;
  background-color: #ffffff;
}

.check-data-item {
  display: flex;
  align-items: center; // 垂直居中
  justify-content: center; // 水平居中
  background-color: #f5f7fa; // 背景色
  border: 1rpx solid #dcdfe6; // 边框
  border-radius: 10rpx; // 圆角
  padding: 10rpx 20rpx; // 内边距
  font-size: 28rpx; // 字体大小
  color: #333; // 字体颜色
  cursor: pointer; // 鼠标悬停时显示手型

  &:hover {
    background-color: #e6f7ff; // 鼠标悬停背景色
    border-color: #91d5ff; // 鼠标悬停边框颜色
  }
}


/* 标题 */
.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

/* 申请人信息 */
.applicant {
  font-size: 26rpx;
  color: #767676;
  margin-bottom: 10rpx;
}

/* 提示信息 */
.tip {
  font-size: 26rpx;
  color: #767676;
  margin-bottom: 10rpx;
}

/* 时间信息 */
.time-info {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #767676;
  margin-bottom: 10rpx;
}

/* 审批状态 */
.status {
  margin-top: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
}

/* 动态状态样式 */
.status-1 {
  color: #3c9cff; // 审批中
}

.status-2 {
  color: #5ac725; // 审批同意
}

.status-3 {
  color: #f56c6c; // 审批驳回
}

.status-4 {
  color: #909399; // 审批撤销
}

/* 加载中和无更多数据提示 */
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.custom-btn {
  width: 320rpx;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  padding: 10px 20px;
  /* 调整内边距 */
  height: 80rpx;
  /* 固定高度 */
  line-height: normal;
  /* 避免文字偏移 */

  &.primary-btn {
    background-color: #007aff;
    /* 自定义主色调 */
    color: white;
    /* 文字颜色 */
  }
}

.page-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 禁止页面滚动 */
}


::v-deep .u-tabs__wrapper {
  background-color: white;
}

.view-search {
  background-color: white;

  .search {
    padding: 10rpx 0rpx 10rpx 0rpx;
  }

  ::v-deep .u-search__content {
    margin: 20rpx 20rpx 20rpx 20rpx !important;
  }
}

.list-li {
  //margin-left: 30rpx;
  //margin-right: 30rpx;
  padding: 20rpx;
  padding-bottom: 10rpx;
}

::v-deep .u-divider {
  margin: 10px 0px 0px 0px;
}

.apply-menu {
  background-color: #f2f2f2;
  padding-top: 30rpx;
  overflow-y: auto;
  //height: 100vh;
}

.list-item {
  border-radius: 20rpx;
  margin: 20rpx;
  background-color: #fff;
}

.topdiv {
  //z-index: 1;
  //display: block;
  //width: 100%;
  //height: 100px !important;
  //background-color: white ;;
  flex-shrink: 0;
  /* 固定高度，不被压缩 */
  background-color: white;
  z-index: 1;
  /* 防止被内容覆盖 */

  .view-search {
    background-color: white;

    ::v-deep .u-search__content {
      background-color: white;
    }
  }
}

.popup {
  padding: 36rpx 0rpx;

  .popup-content {
    margin: 20rpx 10rpx 20rpx 40rpx;
  }
}

.input-first {
  border: 1rpx solid #dadbde;
  display: inline-block;
  width: 420rpx;

  background-color: white !important;
}

.input {
  border: 1rpx solid #dadbde;
  display: inline-block;
  width: 420rpx;
  pointer-events: none;
  background-color: white !important;
}

.span {
  display: inline-block;
  width: 230rpx;
}

.btn {
  display: inline-block;
  width: 280rpx;
  margin-right: 50rpx;
}

.btnS {
  display: inline-block;
  width: 280rpx;
}
</style>
